const Router = require('koa-router');
const svgCaptcha = require('svg-captcha');
const svgToDataURL = require('svg-to-dataurl');
const {v1: uuid} = require('uuid');

const router = new Router({
  prefix: `/api/common`
});

router.get('/captcha', async (ctx, next) => {
  const {type = 'svg', width = 150, height = 50} = ctx.query;
  svgCaptcha.options.width = width;
  svgCaptcha.options.height = height;
  const svgObj = svgCaptcha.create({color: true, background: '#fff'}); // svgObj={text,data}
  const result = {
    captchaId: uuid(),
    svg: svgObj.data.replace(/\"/g, "'"),
  };
  if (type === 'base64') {
    result.url = svgToDataURL(result.svg);
    delete result.svg;
  }
  await helper.redis.set(`verify:img:${result.captchaId}`, svgObj.text.toLowerCase(), 180);

  ctx.set('Content-Type', 'image/svg+xml');
  helper.success(result);
});

module.exports = router;
